package com.cctv.kvtest;

import android.util.Log;


/**
 * 日志工具类 在发布时不显示日志
 */
public class DebugLog {

    private static String className;
    private static String methodName;
    private static int lineNumber;
    public static boolean isDebuggable = BuildConfig.DEBUG;
    /**
     * 最大一次打印长度
     */
    public final static int MAX_LENGTH = 2000;

    private DebugLog() {//不允许
        /* Protect from instantiations */
    }

    private static String createLog(String log) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("(");
        buffer.append(className);
        buffer.append(":");
        buffer.append(lineNumber);
        buffer.append(")");
        buffer.append("[");
        buffer.append(methodName);
        buffer.append("]:");
        buffer.append(log);
        return buffer.toString();
    }

    private static void getMethodNames(StackTraceElement[] sElements) {
        className = sElements[1].getFileName();
        methodName = sElements[1].getMethodName();
        lineNumber = sElements[1].getLineNumber();
    }

    private static void maxPrint(String tag, String msg) {
        if (msg.length() > MAX_LENGTH) {
            int length = MAX_LENGTH + 1;
            String remain = msg;
            int index = 0;
            while (length > MAX_LENGTH) {
                index++;
                Log.e(tag + "[" + index + "]", createLog(remain.substring(0, MAX_LENGTH)));
                remain = remain.substring(MAX_LENGTH);
                length = remain.length();
            }
            if (length <= MAX_LENGTH) {//length>0
                //最后一组
                index++;
                Log.e(tag + "[" + index + "]", createLog(remain));
            }
        } else {
            Log.e(tag, createLog(msg));
        }
    }

    public static void e(String tag, String message) {
        if (!isDebuggable) {
            return;
        }
        getMethodNames(new Throwable().getStackTrace());
        maxPrint(tag, message + "");
    }

    public static void e(String message) {
        if (!isDebuggable) {
            return;
        }
        getMethodNames(new Throwable().getStackTrace());
        maxPrint(className, message + "");
    }

    public static void i(String message) {
        if (!isDebuggable) {
            return;
        }
        getMethodNames(new Throwable().getStackTrace());
        Log.i(className, createLog(message));
    }

    public static void i(String tag,String message) {
        if (!isDebuggable) {
            return;
        }
        getMethodNames(new Throwable().getStackTrace());
        Log.d(tag, createLog(message));
    }

}